package com.xjtu.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjtu.mybatisplus.common.JsonResponse;
import com.xjtu.mybatisplus.common.result.PageResult;
import com.xjtu.mybatisplus.mapper.ArticleMapper;
import com.xjtu.mybatisplus.model.domain.Article;
import com.xjtu.mybatisplus.model.domain.Favorite;
import com.xjtu.mybatisplus.mapper.FavoriteMapper;
import com.xjtu.mybatisplus.service.FavoriteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lsong
 * @since 2023-12-27
 */
@Service
@Slf4j
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {
   @Autowired
   FavoriteMapper favoriteMapper;

   @Autowired
    ArticleMapper articleMapper;
    @Override
    public JsonResponse setFavorite(Long userId, Long articleId) {
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("article_id", articleId);
        if(favoriteMapper.delete(wrapper) == 0) {
            Favorite favorite = new Favorite();
            favorite.setArticleId(articleId).setUserId(userId);
            if(favoriteMapper.insert(favorite) <= 0) return JsonResponse.failure("点赞失败");
        }
        return JsonResponse.success(null);
    }

    @Override
    public JsonResponse<PageResult> getListById(Long userId, Integer page, Integer size) {
        if(userId <= 0) return JsonResponse.failure("意外的用户");

        Page<Article> articlePage = new Page<>(page, size);
        List<Article> records = articleMapper.selectFavById(articlePage, userId);

        com.xjtu.mybatisplus.common.result.PageResult result = new com.xjtu.mybatisplus.common.result.PageResult();
        result.setItems(records);
        result.setTotal(articlePage.getTotal());
        return JsonResponse.success(result);
    }

    @Override
    public JsonResponse getFavStatusById(Long articleId, Long userId) {
        QueryWrapper<Favorite> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("article_id", articleId);
        return favoriteMapper.selectCount(wrapper) > 0 ? JsonResponse.success(1) : JsonResponse.success(0);
    }


}
